<?php

namespace IDock\Insurance\TAIC\Response;

use IDock\Http\Response;
use IDock\IDock\IDockEnums;
use IDock\Insurance\TAIC\TAICEnums;
use IDock\Printer\NonCar\NonCarInquiryPrinter;
use IDock\Printer\NonCar\NonCarInquirySinglePrinter;
use IDock\Printer\Premium\PremiumCoveragePrinter;
use IDock\Printer\Premium\PremiumInquiryPrinter;
use IDock\Printer\SpecialClausesPrinter;

class PremiumInquiryResponse extends AllTAICResponse
{
    /*** @var PremiumInquiryPrinter $printer */
    public $printer = PremiumInquiryPrinter::class;

    public function resolve(): Response
    {
        $body = $this->getBody();
        if (!json_decode($body)) {
            $this->setError('返回数据异常');
            return $this;
        }
        $data = json_decode($body, true);

        if ($this->printer and is_string($this->printer)) {
            $this->printer = new $this->printer;
        }

        $resultCode = $data['resultDTO']['resultCode'] ?? '';
        $resultMess = $data['resultDTO']['resultMess'] ?? '';

        if ($resultCode != 'SUCCESS') {
            $this->setError($resultMess);
            return $this;
        }

        $dealFlag = $data['dealFlag'] ?? '';
        $dealMess = $data['dealMessage'] ?? '';
        $dealMass = $data['dealMassage'] ?? '';

        if ($dealFlag != '1') {
            $this->repeat($dealMess . $dealMass);
            return $this;
        }

        $this->setBody($data);

        return $this;
    }

    public function printerInit(): Response
    {
        $this->printer->inquiryNo = $this->get('carPremiumCaculateNo');

        if ($combosList = $this->get('combosList', [])) {
            foreach ($combosList as $combos) {
                //商业险
                if ($combos['comboNo'] == 'BUSINESS') {
                    $this->printer->biPremiumPrinter->biPremium = (string)($combos['sumPremium'] ?? '0');
                    $this->printer->biPremiumPrinter->biBasePremium = (string)($combos['sumBenchMarkPremium'] ?? '0');
                    $this->printer->biPremiumPrinter->biDiscount = (string)(($combos['sumDiscount'] ?? '0') / 100);

                    $this->printer->biPremiumPrinter->biStartData = date('Y-m-d H:i:s', strtotime($this->get('startDateBus')));
                    $this->printer->biPremiumPrinter->biEndData = date('Y-m-d H:i:s', strtotime('+1 day', strtotime($this->get('endDateBus'))) - 1);

                    $this->printer->premiumFactorPrinter->VCIFactorAppend('商业险风险评级(交强)', 'VCIElrLevelCTP', $combos['elrLevelCTP'] ?? '');
                    $this->printer->premiumFactorPrinter->VCIFactorAppend('商业险风险评级(商业)', 'VCIElrLevelCOM', $combos['elrLevelCOM'] ?? '');
                    $this->printer->premiumFactorPrinter->VCIFactorAppend('商业险风险评级(整单)', 'VCIElrLevelAll', $combos['elrLevelAll'] ?? '');
                    $this->printer->premiumFactorPrinter->VCIFactorAppend('商业险天马指数地板价', 'VCITianMaIndexFloorPrice', $combos['tianMaIndexFloorPrice'] ?? '');
                    $this->printer->premiumFactorPrinter->VCIFactorAppend('商业险天马指数地标费', 'VCITianMaIndexBasicPrice', $combos['tianMaIndexBasicPrice'] ?? '');

                    if ($coverageList = $combos['itemKindList'] ?? '') {
                        foreach ($coverageList as $coverage) {
                            $premiumCoveragePrinter = new PremiumCoveragePrinter();

                            $premiumCoveragePrinter->coverageCode = array_search($coverage['kindCode'], TAICEnums::$coverageCode) ?? '';
                            $premiumCoveragePrinter->coverageName = IDockEnums::$coverageCode[$premiumCoveragePrinter->coverageCode];

                            $premiumCoveragePrinter->basePremium = $coverage['benchMarkPremium'] ?? '';
                            $premiumCoveragePrinter->premium = $coverage['premium'] ?? '';
                            $premiumCoveragePrinter->amount = $coverage['amount'] ?? '';
                            $premiumCoveragePrinter->discount = (string)(($coverage['discount'] ?? '') / 100);
                            $premiumCoveragePrinter->unitAmount = $coverage['unitAmount'] ?? '';
                            $premiumCoveragePrinter->serviceTimes = $coverage['quantity'] ?? '';
                            $premiumCoveragePrinter->quantity = $coverage['quantity'] ?? '';

                            $this->printer->coverageListAppend($premiumCoveragePrinter);
                        }
                    }

                    if ($engageList = $combos['engageList'] ?? []) {
                        foreach ($engageList as $item) {
                            $specialClausesPrinter = new SpecialClausesPrinter();
                            $specialClausesPrinter->clauseCode = $item['engageCode'] ?? '';
                            $specialClausesPrinter->clauseName = $item['engageTitle'] ?? '';
                            $specialClausesPrinter->clauseContent = $item['engageContent'] ?? '';
                            $specialClausesPrinter->riskType = 'VCI';
                            $specialClausesPrinter->autoFlag = '1';

                            $this->printer->specialClausesAppend($specialClausesPrinter);
                        }
                    }
                }

                //交强险
                if ($combos['comboNo'] == 'JQXCOMBO001') {
                    $this->printer->ciPremiumPrinter->ciPremium = (string)($combos['sumPremium'] ?? '0');
                    $this->printer->ciPremiumPrinter->ciBasePremium = (string)($combos['sumBenchMarkPremium'] ?? '0');
                    $this->printer->ciPremiumPrinter->ciDiscount = (string)(($combos['sumDiscount'] ?? '0') / 100);

                    $this->printer->ciPremiumPrinter->ciStartData = date('Y-m-d H:i:s', strtotime($this->get('startDate')));
                    $this->printer->ciPremiumPrinter->ciEndData = date('Y-m-d H:i:s', strtotime('+1 day', strtotime($this->get('endDate'))) - 1);

                    $this->printer->premiumFactorPrinter->TCIFactorAppend('交强险风险评级(交强)', 'TCIElrLevelCTP', $combos['elrLevelCTP'] ?? '');
                    $this->printer->premiumFactorPrinter->TCIFactorAppend('交强险风险评级(商业)', 'TCIElrLevelCOM', $combos['elrLevelCOM'] ?? '');
                    $this->printer->premiumFactorPrinter->TCIFactorAppend('交强险风险评级(整单)', 'TCIElrLevelAll', $combos['elrLevelAll'] ?? '');
                    $this->printer->premiumFactorPrinter->TCIFactorAppend('交强险天马指数地板价', 'TCITianMaIndexFloorPrice', $combos['tianMaIndexFloorPrice'] ?? '');
                    $this->printer->premiumFactorPrinter->TCIFactorAppend('交强险天马指数地标费', 'TCITianMaIndexBasicPrice', $combos['tianMaIndexBasicPrice'] ?? '');


                    if ($engageList = $combos['engageList'] ?? []) {
                        foreach ($engageList as $item) {
                            $specialClausesPrinter = new SpecialClausesPrinter();
                            $specialClausesPrinter->clauseCode = $item['engageCode'] ?? '';
                            $specialClausesPrinter->clauseName = $item['engageTitle'] ?? '';
                            $specialClausesPrinter->clauseContent = $item['engageContent'] ?? '';
                            $specialClausesPrinter->riskType = 'TCI';
                            $specialClausesPrinter->autoFlag = '1';

                            $this->printer->specialClausesAppend($specialClausesPrinter);
                        }
                    }
                }
            }
        }
        //存拓展字段
        $this->printer->argc['totalAssets'] = $this->visitor->getExtInfoVisitor()->argc['totalAssets'] ?? '';
        $this->printer->argc['operatingIncome'] = $this->visitor->getExtInfoVisitor()->argc['operatingIncome'] ?? '';
        $this->printer->argc['employeesNumber'] = $this->visitor->getExtInfoVisitor()->argc['employeesNumber'] ?? '';
        $this->printer->argc['mainBusiness'] = $this->visitor->getExtInfoVisitor()->argc['mainBusiness'] ?? '';
        $this->printer->argc['industryMainCategory'] = $this->visitor->getExtInfoVisitor()->argc['industryMainCategory'] ?? '';
        $this->printer->argc['industrySubCategory'] = $this->visitor->getExtInfoVisitor()->argc['industrySubCategory'] ?? '';
        //车船税
        if ($taxData = $this->get('pcCarShipTaxInfoDto', [])) {
            $this->printer->carTaxPrinter->thisYearTax = $taxData['taxActual'] ?? '';
            $this->printer->carTaxPrinter->overdue = $taxData['lateFee'] ?? '';
            $this->printer->carTaxPrinter->payBackTax = $taxData['previousPay'] ?? '';
            $this->printer->carTaxPrinter->carShipTax = $taxData['sumTax'] ?? '';
        }

        $this->printer->ncdFactor = $this->get('premfactor1');
        $loyalty = ['0' => '新', '1' => '续', '2' => '转'];
        $this->printer->premiumFactorPrinter->VCIFactorAppend('商业险出险次数', 'commercialNum', $this->get('commercialNum'));
        $this->printer->premiumFactorPrinter->VCIFactorAppend('商业险理赔次数', 'commercialNum', $this->get('commercialNum'));
        $this->printer->premiumFactorPrinter->VCIFactorAppend('商业险忠诚度', 'BIRenewalType', $loyalty[$this->get('insuredStatus')] ?? '');

        $this->printer->premiumFactorPrinter->TCIFactorAppend('交强险出险次数', 'trafficInsuranceNum', $this->get('trafficInsuranceNum'));
        $this->printer->premiumFactorPrinter->TCIFactorAppend('交强险理赔次数', 'trafficInsuranceNum', $this->get('trafficInsuranceNum'));
        $this->printer->premiumFactorPrinter->TCIFactorAppend('交强险忠诚度', 'CIRenewalType', $loyalty[$this->get('insuredStatus')] ?? '');
        $this->printer->premiumFactorPrinter->ComFactorAppend('自主渠道系数', 'premfactor2', $this->get('premfactor2'));
        $this->printer->premiumFactorPrinter->ComFactorAppend('自主核保系数', 'premfactor3', $this->get('premfactor3'));
        $this->printer->premiumFactorPrinter->ComFactorAppend('交通违法系数', 'ciLegalFactor', $this->get('premfactor4'));
        $this->printer->premiumFactorPrinter->ComFactorAppend('自主定价系数', 'selfPricingCoef', $this->get('premfactorPrice'));

        return $this;
    }

    private function repeat($errorMsg)
    {

        if (preg_match('/终保日期 ([\d -\:]+)/', $errorMsg, $matches)) {

            if ($matches[1] ?? '') {
                $this->printer->success = false;
                $this->printer->repeatInsuredFlg = true;
                $this->printer->repeatMessage = $errorMsg;
                $this->printer->repeatInsurePrinter = [
                    'ciStartData' => date('Y-m-d H:i:s', strtotime($matches[1] ?? '')),
                ];
                return;
            }
        }
        $this->setError($errorMsg);
        $this->printer->success = false;
    }
}
